package net.tngou.iask.action.api;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.math.NumberUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.abel533.echarts.Legend;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.Axis;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Position;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.data.LegendData;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.series.Series;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.style.itemstyle.Emphasis;
import com.github.abel533.echarts.style.itemstyle.Normal;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.entity.Statistic;
import net.tngou.iask.jdbc.OrderType;
import net.tngou.iask.pojo.Accessresult;
import net.tngou.iask.pojo.Answer;
import net.tngou.iask.pojo.Patient;
import net.tngou.iask.pojo.Question;
import net.tngou.iask.service.QuestionService;
import net.tngou.iask.service.StatisticService;
import net.tngou.iask.util.DateUtil;

/**
 * 统计接口
 * @author tngou@tngou.net
 *
 */
public class EchartsApi  extends BaseAction{

	
	
	
	/**
	 * 性别比例饼图
	 */
	public void	sexpie() {
		if(user==null){
			run_nologin();return;
		}
		StatisticService service = new StatisticService();
		Statistic statistic = service.getPatient(user.getMain());
		Option option = new Option();
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		option.tooltip().trigger(Trigger.item).formatter("{b} : {c} ({d}%)");
		Pie pie = new Pie();
		pie.data(new Data("男", statistic.getPatient_male()),new Data("女", statistic.getPatient_female()));
		option.series(pie);	
		printJson(toJsonP(toJSON(option)));
		
	}
	/**
	 * 年龄段
	 */
	public void patientagepie() {
		if(user==null){
			run_nologin();return;
		}
		StatisticService service = new StatisticService();
		List<Statistic> list = service.getPatientAge(user.getMain());
		Option option = new Option();
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		option.tooltip().trigger(Trigger.item).formatter("{b} : {c} ({d}%)");
		Pie pie = new Pie();
		List<Data> datas = new ArrayList<>();
		list.forEach(e->{
			Data data = new Data();
			data.setName(e.getName());
			data.setValue(e.getValue());
			datas.add(data);
		});
		pie.data(datas.toArray());
		option.series(pie);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 月患者数
	 */
	public void patientmonthbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=3;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getPatientList(user.getMain(), date, 2);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 周患者数
	 */
	public void patientweekbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=4;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getPatientList(user.getMain(), date, 1);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 日患者
	 */
	public void patientdayline() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=7;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getPatientList(user.getMain(), date, 0);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Line line = new Line();	
		line.data(values);
		option.series(line);	
		printJson(toJsonP(toJSON(option)));
	}
	
	
	/**
	 * 月患者数
	 */
	public void curemonthbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=3;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getCureList(user.getMain(), date, 2);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 周患者数
	 */
	public void cureweekbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=4;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getCureList(user.getMain(), date, 1);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 日患者
	 */
	public void curedayline() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=7;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getCureList(user.getMain(), date, 0);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Line line = new Line();	
		line.data(values);
		option.series(line);	
		printJson(toJsonP(toJSON(option)));
	}
	
	
	
	/**
	 * 最常见疾病治疗统计
	 */
	public void	curebar() {
		if(user==null){
			run_nologin();return;
		}
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getCureList(user.getMain());
		int size=list.size()>10?10:list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size()&&i<10; i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
		
	}
	
	public void	accessline() {
		if(user==null){
			run_nologin();return;
		}
		StatisticService service = new StatisticService();
		
		Object names[]=new Object[7];
		
		Object values[]=new Object[7];
		Object values2[]=new Object[7];
		for (int i = 0; i < 7; i++) {
			Statistic element=service.getAccess(user.getMain(), 6-i, 1);//
			Statistic element2=service.getAccessList(user.getMain(), 6-i, 1, 2);//
			values[i]=element.getValue();
			values2[i]=element2.getValue();
			names[i]=DateUtil.format(LocalDateTime.now().plusDays(-(6-i)), "MM-dd");
		}
		Option option = new Option();
	
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		option.tooltip().trigger(Trigger.item);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Line line = new Line();
		line.name("创建");
		line.data(values);
		Line line2 = new Line();
		line2.name("完成");
		line2.data(values2);
		option.series(line,line2);	
		printJson(toJsonP(toJSON(option)));
		
	}
	
	/**
	 * 月患访问
	 */
	public void accessmonthbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=3;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getAccessList(user.getMain(), date, 2);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 周访问
	 */
	public void accessweekbar() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=4;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getAccessList(user.getMain(), date, 1);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Bar bar = new Bar();	
		bar.data(values);
		option.series(bar);	
		printJson(toJsonP(toJSON(option)));
	}
	
	/**
	 * 日访问
	 */
	public void accessdayline() {
		if(user==null){
			run_nologin();return;
		}
		int date=(int) ask.getId();
		if(date==0)date=7;
		StatisticService service = new StatisticService();
		List<Statistic> list =  service.getAccessList(user.getMain(), date, 0);
		int size=list.size();
		Object names[]=new Object[size];
		Object values[]=new Object[size];
		
		for (int i = 0; i < list.size(); i++) {
			Statistic element= list.get(i);
			names[i]=element.getName();
			values[i]=element.getValue();
		}
		Option option = new Option();	
		option.tooltip().trigger(Trigger.item);
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		CategoryAxis categoryAxis = new CategoryAxis();
//		ValueAxis xAxis = new ValueAxis();
		categoryAxis.data(names);
  
	    option.xAxis(categoryAxis);
	    ValueAxis yAxis = new ValueAxis();
	    yAxis.axisLabel();    
	    option.yAxis(yAxis);
		Line line = new Line();	
		line.data(values);
		option.series(line);	
		printJson(toJsonP(toJSON(option)));
	}
	
	
	
	/**
	 * 自定义统计
	 * type类型：0（判断）、1（单选） 2（多选） 3（填空数字）	
	 * question：问题
	 * patient：病人
	 */
	@SuppressWarnings("unchecked")
	public void analysis() {
		if(user==null){
			run_nologin();return;
		}
	
		String question = request.getParameter("q");//问题
		String patient = request.getParameter("p");//患者
		if(isEmpty(question,patient)||!NumberUtils.isNumber(question)||!NumberUtils.isNumber(patient))
		{
			run_false("请求参数不正确!");return;
		}
		Question q = new Question().get(Long.parseLong(question));
		Patient p = new Patient().get(Long.parseLong(patient));
		if(isEmpty(q,p)){
			run_false("请求数据不正确!");return;
		}
		List<Accessresult> list = (List<Accessresult>) service.getList("patient="+p.getId()+" AND question="+q.getId(),"time",OrderType.ASC,Accessresult.class);
		Option option = new Option();
		option.grid().top("3%").left("3%").right("4%").bottom(20).containLabel(true);
		option.tooltip().trigger(Trigger.item).formatter("{b} : {c} ({d}%)");
		
		
		if(q.getType()==0)// 判断 饼图
		{
			int yes=0;//是选项
			int no=0;//否选项
			for (Accessresult e : list) {
				if(e.getValue()==1)yes++;
				if(e.getValue()==0)no++;
			}

			option.legend().orient(Orient.vertical).x("left").data("是","否");
			Pie pie = new Pie();
			List<Data> datas = new ArrayList<>();
			
			Data datayes = new Data();
			datayes.setName("是");
			datayes.setValue(yes);
			datas.add(datayes);
			
			Data datano = new Data();
			datano.setName("否");
			datano.setValue(no);
			datas.add(datano);
			pie.radius("50%", "70%");
			ItemStyle label= new ItemStyle();
			label.normal(new Normal().show(false).position(Position.center));
			label.emphasis(new Emphasis().show(true).textStyle(new TextStyle().fontSize(30).fontWeight("bold")));
			pie.label(label);
			pie.data(datas.toArray());
			
			option.series(pie);	
			printJson(toJsonP(toJSON(option)));
		}else if(q.getType()==1||q.getType()==2)//单选  多选  饼图 
		{
			QuestionService service = new QuestionService();
			List<Answer> answers = service.getAnswer(q.getId());
			Map<String, Integer> map= new HashMap<>();
			list.forEach(e->{
				String key =e.getValue()+"";
				if(map.get(key)==null){
					map.put(key, 1);
				}
				else{
					map.put(key, map.get(key)+1);
				}
			});
			
			Legend legend = new Legend();
			List<LegendData> ldatalist = new ArrayList<>();
			List<Data> datalist = new ArrayList<>();
			answers.forEach(e->{
				LegendData ldata = new LegendData(e.getName());
				ldatalist.add(ldata);
				Data data = new Data();				
				data.setName(e.getName());
				data.setValue(map.get(e.getValue()+"")==null?0:map.get(e.getValue()+""));
				datalist.add(data);
				
			});
			legend.orient(Orient.vertical).x("left").data(ldatalist.toArray());
			option.legend(legend);
			option.series(new Pie().data(datalist.toArray()));	
			printJson(toJsonP(toJSON(option)));
		}else if(q.getType()==3)//填空
		{
			int size=list.size();
			Object names[]=new Object[size];
			Object values[]=new Object[size];
			
			for (int i = 0; i < list.size(); i++) {
				Accessresult e= list.get(i);
				names[i]=DateUtil.format(e.getTime().toLocalDateTime(), "yy-MM-dd");
				values[i]=e.getValue();
			}
			CategoryAxis categoryAxis = new CategoryAxis();
//			ValueAxis xAxis = new ValueAxis();
			categoryAxis.data(names);
	  
		    option.xAxis(categoryAxis);
		    ValueAxis yAxis = new ValueAxis();
		    yAxis.axisLabel();    
		    option.yAxis(yAxis);
			Line line = new Line();	
			line.data(values);
			option.series(line);
			printJson(toJsonP(toJSON(option)));
		}
		
		
	}
	
	
	
	
	
	
	private JSONObject toJSON(Option option)
	{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("option", option);
		return jsonObject;
		
	}
	
	
}
